var express = require('express');
var mongodb = require("../data/base");
var https = require("https");
const { json } = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  let pagesize = 20;
  let pagenum = 0;
  let pagevalue = 1;
  let page1 = {}
  console.log(req.query)
  mongodb.taobao.find((err,data)=>{
    mongodb.taobao.count((err,count)=>{
      pagenum = Math.ceil(count/pagesize);
      
      if(req.query.page){
        pagevalue = req.query.page;
      }else{
        pagevalue = 1;
      }

      let page = (pagevalue - 1) * pagesize;
      let sql = null;

      if(req.query.sort){
        if(req.query.sort === "asc"){
          mongodb.taobao.find().skip(page).limit(pagesize).sort({"pPrice":1}).then((data)=>{
            page1.pagesize = pagenum;
            page1.pagecontent = data;
            res.send(page1)
          })
        }else{
          mongodb.taobao.find().skip(page).limit(pagesize).sort({"pPrice":-1}).then((data)=>{
            page1.pagesize = pagenum;
            page1.pagecontent = data;
            res.send(page1)
          })
        }
      }else{
        mongodb.taobao.find().skip(page).limit(pagesize).then((data)=>{
            page1.pagesize = pagenum;
            page1.pagecontent = data;
            res.send(page1)
        })
      }

    })
  })
});

router.post("/detaills",function(req,res,next){
  mongodb.taobao.find({"_id":req.body.sid},(err,data)=>{
    res.send(data)
  })
})

router.post("/regit",function(req,res,next){
  if(req.body.submit){
    new mongodb.user({
        "username":req.body.username,
        "password":req.body.password,
        "tel":req.body.tel
      }).save((err,data)=>{
        res.redirect("http://localhost:3000/login.html")
      })
  }else{
    mongodb.user.find({"username":req.body.user},(err,data)=>{
        console.log(!!data.length)
        if(data.length){
          res.send({'status':1,"meg":"用户名重名"});
        }else{
          res.send({'status':0,"meg":"用户名可以使用"});
        }
      })
  }
  
})


router.post("/login",function(req,res,next){
  mongodb.user.find({"username":req.body.username},(err,data)=>{
    console.log(data[0].username)
    if(data[0].username){
      if(data[0].password == req.body.password){
        res.send({'status':200,"meg":"登录成功！！！","username":data[0].username});
      }else{
        res.send({'status':402,"meg":"用户名或密码错误！！！"})
      }
    }else{
      res.send({'status':401,"meg":"用户名不存在！！！"});
    }
  })
})

router.post("/cartlist",function(req,res,next){
  mongodb.taobao.find({},(err,data)=>{
    res.send(data)
  })
})

router.get("/header",function(req,res,next){
  console.log(req.query.val)
  https.get(`https://www.samsungeshop.com.cn/api/product/psp/getKeywords/0?keyword=${req.query.val}`,(result)=>{
  result.on("data",(a)=>{
      res.send(JSON.parse(a.toString()).data)
    })
  })
})



module.exports = router;
